/**
 * @file detail.tsx
 * @description 待配送详情
 */
import React,{ useState,} from 'react';
import { Box, FlatList, useToast, Avatar, HStack, VStack, Text, Spacer, Center, Button,ScrollView,AlertDialog,Pressable,} from 'native-base';
import HeaderScreen from '../../components/header';
import { useMount } from "ahooks";
import * as request from "../../request/common";
import {useFocusEffect} from '@react-navigation/native';
import GlobalEmitter from "../../utils/global";
import { updatePKList,getPKList, } from "../../utils/untils";
import { PermissionsAndroid } from 'react-native';


enum orderType {
  Production, // 生产单
  Outsource, // 外协
  Pick // 配料单
}

const DispatchingDetailsScreen: React.FC<ComponentProp> = ({ navigation,route }) => {
  /******变量******/
  const routeParams: any = route?.params;
  const [isOpen, setIsOpen] = useState(false);
  const onClose = () => setIsOpen(false);
  const cancelRef = React.useRef(null);
  const toast = useToast();
  const [dispatchingList, setDispatchingList] = useState([]); // 配送详情列表
  const [currentModal, setcurrentModal] = useState<any>({}); // 当前选择行
  const [pkList, setPKList] = useState([]); // 已配料id列表

  /******生命周期******/
  useMount(async() => {
    setPKList( await getPKList());
  });

  /**
   * 导航获取焦点、失去焦点
   */
   useFocusEffect(
    React.useCallback(() => {
      getDispatchingItemList();
    }, []),
  );

  /******方法******/

  /**
   * 上车
   */
  const handlePutIn = async ()=>{
  if(currentModal.type == orderType.Outsource || currentModal.type == orderType.Production){ // 生产单、 外协 出库
    request.putInStorage(currentModal?.factory_order_id).then((res: any) => {
      onClose();
      if (res?.code == 40020) {
        toast.show({
          placement: "top",
          description:'上车成功'
        });
        getDispatchingItemList();
      }else{
        toast.show({
          placement: "top",
          description: res?.message || '上车失败'
        });
      }
    });
  }else {  // 配料 出库，本地缓存状态，不提交服务器
    await updatePKList(currentModal?.id, 'add');
    toast.show({
      placement: 'top',
      description: '上车成功',
    });
    setPKList( await getPKList());
    getDispatchingItemList(); 
  }
   
  }

  /**
   * 发车
   */
  const handleDepart = ()=>{
    request.updateOrderStatus(routeParams?.orderInfo?.code_id).then((res: any) => {
         if (res?.code == 40020) {
           toast.show({
            placement: "top",
             description:'发车成功'
           });
           navigation?.goBack();
           GlobalEmitter.emit('updateOrderStatus5000', {
             codeId: routeParams?.orderInfo?.code_id,
           });
         }else{
           toast.show({
            placement: "top",
             description: res?.message || '发车失败'
           });
         }
     });
   }

  /**
   * 获取配送列表
   */
  const getDispatchingItemList = ()=>{
    let p1 = new Promise((resolve, reject) => { // 获取生产单
      request.getFactoryListByOrder(routeParams?.orderInfo?.code_id).then((res: any) => {
        if (res?.code == 40020) {
          resolve(res?.data?.list);
        }
      });
    })
    let p2 = new Promise((resolve, reject) => { // 获取外协单
      request.getFactoryListByOrder(routeParams?.orderInfo?.code_id,'1').then((res: any) => {
        if (res?.code == 40020) {
          resolve(res?.data?.list);
        }
      });
    })
    let p3 = new Promise((resolve, reject) => { // 获取配料单
      request.getPickingListByOrder(routeParams?.orderInfo?.code_id).then((res: any) => {
        if (res?.code == 40020) {
          resolve(res?.data?.list);
        }
      });
    })

    Promise.all([p1, p2,p3]).then((result: any) => {
      let allList: any= [];
      let prodectList = result[0];
      let outsourceList = result[1];
      let pickList = result[2];
      prodectList.forEach((element: any) => {
        element.type=orderType.Production; // 生产单
        allList.push(element);
      });
      outsourceList.forEach((element: any) => {
        element.type=orderType.Outsource; // 外协单
        allList.push(element);
      });
      pickList.forEach((element: any) => {
        element.type=orderType.Pick; // 配料单
        allList.push(element);
      });
      setDispatchingList(allList);
    }).catch((error) => {

    })
    
  }
  /**
   * 渲染列表
   */
  const renderItem = (item: any) => {
    let typeTitle = "";
    let codeId= "";
    let btnTitle ="";
    if(item.type == orderType.Production){
      typeTitle ="生产单";
      if(item?.factory_order_status == 30){ // 已出库
        btnTitle = "";
      }else{
        btnTitle = "扫描上车";
        if(item?.packages == 0){ // 没有上传包装清单
          btnTitle ="点击上车";
        }else if(item?.packages == item?.out_stock_packages){
          btnTitle = "";
        }else if(item?.out_stock_packages  >0){
          btnTitle = "继续扫描";
        }
      }
      codeId = item.factory_code_id;
    }else if(item.type == orderType.Outsource){
      typeTitle ="外协单";
      if(item?.factory_order_status == 30){ // 已出库
        btnTitle = "";
      }else{
        btnTitle = "点击上车";
      }
      codeId = item.factory_code_id;
    }else if(item.type == orderType.Pick){
      typeTitle ="配料单";
      let findIndex = pkList.findIndex((element: any) => element == item.id);
      if(item?.status == 30 && findIndex != -1){
        item.status_name = '已上车';
      }
      if(item?.status == 30 && findIndex == -1){ // 已配料
        btnTitle = "点击上车";
      }else{
        btnTitle = "";
      }
      codeId = item.pick_up_code_id;
    }
    return (
      <Box
        key={item.id}
        borderWidth="0.3"
        borderColor="muted.300"
        rounded="xl"
        px="4"
        py="4"
        mx="4"
        my="4">
        <HStack w="100%" justifyContent="space-between">
          <VStack w="70%" textAlign="left" space="0.5" pl="0">
            <Text color="coolGray.600" bold>
              {typeTitle}:<Text>{'  '}{codeId}</Text>
            </Text>
            {item.type == orderType.Pick ? <Text color="coolGray.600">
              类型:<Text bold>{'  '}{item?.goods_type_name}</Text>
            </Text> : <Text color="coolGray.600">
              包数:<Text bold>{'  '}{item?.packages}</Text>
            </Text>}
            <HStack>
              {item.type == orderType.Pick ? <Text color="coolGray.600">
                状态:<Text bold>{'  '}{item?.status_name =='已出库'?'已上车': item?.status_name}</Text>
              </Text> :  <Text color="coolGray.600">
                已上车:<Text bold>{'  '}{item?.out_stock_packages}</Text>
              </Text> }
              <Pressable
                onPress={() => {
                  navigation?.navigate('DispatchingDetailsStatusScreen',{productionInfo:item,orderInfo:routeParams?.orderInfo});
                }}>
                {
                  item.type == orderType.Production &&  item?.factory_order_status == 26 && item?.out_stock_packages >0 ?  <Text ml="10" color="blue.500">
                  查件
                </Text> : null
                }
              </Pressable>
            </HStack>
          </VStack>
          <Spacer />
          <Center w="30%">
            {btnTitle?.length > 0 ?   <Button
              bg="#4F94F9"
              size="sm"
              _pressed={{bg: '#4F94F9'}}
              onPress={async () => {
                if(item.type == orderType.Production){
                  if(item?.packages == 0){ // 没有上传包装清单
                    setcurrentModal(item);
                    setIsOpen(!isOpen);
                  }else{
                    // 尝试获取权限
                    try {
                     let granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA);
                     if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                      console.log("You can use the camera");
                    } else {
                      console.log("Camera permission denied");
                    }
                    } catch (err) {
                      console.warn(err);
                    }
                   
                    navigation?.navigate('ScanScreen',{productionInfo:item});
                  }
                }else if(item.type == orderType.Pick || item.type == orderType.Outsource){
                  setcurrentModal(item);
                  setIsOpen(!isOpen);
                }
              }}>
              {btnTitle}
            </Button> : null }
          </Center>
        </HStack>
      </Box>
    );
  };

  let headerTitle = '';
  if (currentModal.type == orderType.Production) {
    headerTitle = '生产单';
  } else if (currentModal.type == orderType.Outsource) {
    headerTitle = '外协单';
  } else if (currentModal.type == orderType.Pick) {
    headerTitle = '配料单';
  }
  return (
    <Box bg="gray.100" borderRadius="md" w="100%" h="100%">
      <HeaderScreen navigation={navigation}  title={routeParams?.orderInfo?.code_id}></HeaderScreen>
      <HStack direction="column" space={1} py="4" px="4"  borderBottomWidth="0.3"
            borderColor="muted.300"  >
        <Text>地址:<Text bold>{'  '}{routeParams?.orderInfo?.address_detail}</Text></Text>
        <Text>司机:<Text bold>{'  '}{routeParams?.orderInfo?.driver_name}{routeParams?.orderInfo?.driver_mobile? "，"+routeParams?.orderInfo?.driver_mobile: ''}</Text></Text>
      </HStack>
      <ScrollView mb="20">
      {dispatchingList.map((item: any)=>renderItem(item))}
      </ScrollView>
      {
        routeParams?.orderInfo?.order_status == 4000 && routeParams?.orderInfo?.driver_name !=""?  <Box w="100%" h="20"  bg="white" position="absolute" bottom="0" alignItems="center" ><Button  isLoadingText="发车中..." w="90%"   bg="#4F94F9" _pressed={{ bg:"#4F94F9" }} onPress={handleDepart} >
        发车
      </Button></Box> : null
      }
      <AlertDialog leastDestructiveRef={cancelRef} isOpen={isOpen} onClose={onClose}>
        <AlertDialog.Content>
          <AlertDialog.CloseButton />
          <AlertDialog.Header alignItems="center">{headerTitle}</AlertDialog.Header>
          {currentModal.type == orderType.Production || currentModal.type == orderType.Outsource ?
          <AlertDialog.Body alignItems="center" >
           <Text>{currentModal?.address_detail}</Text>
           <Text>总:<Text color="#e73223">{currentModal?.packages}</Text>包</Text>
           <Text>确认上车吗?</Text>
          </AlertDialog.Body> 
          :
          <AlertDialog.Body alignItems="center" >
          <Text>{currentModal?.address_detail}</Text>
          <Text>{currentModal?.goods_type_name}配料单</Text>
          <Text>确认上车吗?</Text>
        </AlertDialog.Body>
        }
          <AlertDialog.Footer justifyContent="space-between" h="10" py="0" >
          <Button variant="unstyled" colorScheme="coolGray" onPress={onClose} ref={cancelRef}>
                再看看
              </Button>
              <Button colorScheme="danger" variant="unstyled" _text={{ color: "#e73223"}} color="#4F94F9" onPress={handlePutIn}>
                确认上车
              </Button>
          </AlertDialog.Footer>
        </AlertDialog.Content>
      </AlertDialog>
    </Box>
  );
};

export default DispatchingDetailsScreen;
